<!DOCTYPE html>
<html lang="en">
  <head>
    <title>用户登录</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./css/style.css">
    <link rel="stylesheet" href="./css/login.css">
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  </head>
  <body>
    <div id="root">
      <div class="login">
        <div class="content">
          <div class="main">
            <div class="header">
              <h2 class="title">用户登录</h2>
              <div class="register" @click="goRegister">用户注册</div>
            </div>
            <el-form ref="form" :rules="rules" :model="form" class="table">
              <el-form-item prop="username">
                <el-input v-model.trim="form.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model.trim="form.password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item class="submit">
                <el-button type="primary" @click="onSubmit" style="width:100%">确定</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script>
      new Vue({
        el: "#root",
        data () {
          return {
            form:{
              username: undefined,
              password: undefined
            },
            rules: {
              username: [
                { required: true, message: '用户名不能为空', trigger: 'blur' }
              ],
              password: [
                { required: true, message: '密码不能为空', trigger: 'blur' }
              ]
            }
          }
        },
        created () {
          sessionStorage.clear()
        },
        methods: {
          onSubmit () {
            this.$refs["form"].validate(async valid => {
              if (valid) {
                axios.post("http://localhost:3333/user/login",this.form).then(res => {
                  if (res.data.code == 200) {
                    console.log(res.data);
                    sessionStorage.setItem("token",res.data.data.token)
                    sessionStorage.setItem("username",res.data.data.username)
                    window.location.href = "./index.html"
                  } else {
                    this.$message.error(res.data.msg)
                  }
                })
              }
            })
          },
          goRegister () {
            window.location.href = "./register.html"
          },
        },
      })
    </script>
  </body>
</html>